<template>
	<view>
		<my-chat ref="myChatRef" :chatList="chatList" :imgList="chatImgs" :msgObjectData="msgObjectData"
			:isSendMsg="isShowSend" :sendTitle="sendTitle" :isGx="isGx" @sendMsg="sendMsg" @gotoUserSet="gotoUserSet"
			@showRedPkg="showRedPkg" @closeUserMsg="closeUserMsg" @withdrawUserMsg="withdrawUserMsg"
			@sendAddUser="sendAddUser" @getChatListByPage="getChatListByPage" @handleAudio="handleAudio"></my-chat>

		<!-- 红包信息 -->
		<chat-redpkg-animation @closeHbFun="closeHbFun" :showHbMsg="showHbMsg" :rbagmodelshow="isShowHb"
			@openHbFun="openHbFun" :openbrnanimation="openbrnanimation"
			:openrbagmodelshow="openrbagmodelshow"></chat-redpkg-animation>
	</view>
</template>

<script>
	//1，引入核心组件
	import myChat from '@/components/content/my-new-chat/my-chat.vue'
	import chatRedpkgAnimation from '@/components/content/my-chat/common/chat-redpkg/redpkg-animation.vue'

	//2，引入vuex
	import {
		mapState,
		mapMutations,
		mapActions,
		mapGetters
	} from 'vuex'

	//3，引入工具类
	import {
		getNowTime
	} from '@/utils/time/time.js'

	//4，引入实体类对象
	import {
		msgHomeData,
		msgChatData
	} from '@/object/msg.js'

	//5，引入网络请求
	import {
		queryFriendRemarks
	} from '@/api/http/msg/friend.js'
	import {
		queryRedPkgById,
		robByUser
	} from '@/api/http/msg/redpkg.js'
	import {
		queryIsBlack
	} from '@/api/http/msg/relation.js'

	export default {
		components: {
			myChat,
			chatRedpkgAnimation
		},
		data() {
			return {
				//我的信息
				userId: uni.getStorageSync('userId'),
				head: uni.getStorageSync('head'),
				nickname: uni.getStorageSync('nickname'),

				msgObjectData: {}, //聊天对象信息

				allChatList: [], //所有的聊天信息
				chatList: [], //聊天主要信息
				chatImgs: [], //图片信息

				isGx: true, //是否为互相为好友
				isBlackUser: false, //对方是否将你加入黑名单
				isMe: false, //是否为自己
				isShowSend: false, //是否展示禁言框
				sendTitle: '添加好友后聊天', //禁言标题

				pageSize: 20,
				pageNum: 1,
				total: 0,

				//红包信息
				showHbMsg: {},
				isShowHb: false,
				openbrnanimation: {}, //红包点击动画
				openrbagmodelshow: false,

				//语音播放
				innerAudioContent: uni.createInnerAudioContext(),

				isShowGoto: false, //是否跳转到最底部

			}
		},
		computed: {
			...mapState('m_chat', ['chatData', 'topMsgData', 'notTopMsgData']),
			...mapGetters('m_chat', ['getChatData']),
		},
		watch: {
			chatData() {
				//console.log(123123412)
			},
			topMsgData() {
				//console.log(123)
				/* this.chatList = []
				this.chatImgs = []
				this.pageNum = 1
				this.getChatList(1)
				this.msgReag(this.msgObjectData)

				//获取最后一条
				var lastMsg = this.chatList[this.chatList.length - 1]
				if (lastMsg.sendId == this.userId) {
					this.gotoScrollBottom()
				} */
				// console.log(lastMsg)
				// console.log('这里1')
				/* var newMsg = this.topMsgData[0]
				if (newMsg.type == 2 && newMsg.id == this.msgObjectData.id) {
					this.chatList = []
					this.chatImgs = []
					var pageAllSize = this.pageSize * this.pageNum
					this.pageNum = 1
					this.pageSize = pageAllSize + 1
					this.getChatList(1)
					this.msgReag(this.msgObjectData)
					//获取最后一条
					var lastMsg = this.chatList[this.chatList.length - 1]

					if (lastMsg.sendId == this.userId) {
						this.gotoScrollBottom(50)
					} else {
						//this.isShowGoto = true
						this.gotoScrollBottom(50, false)
					}
				} */
				//this.pageSize = 20
				
				
				var newMsg = this.notTopMsgData[0]
				if (newMsg.type == 2 && newMsg.id == this.msgObjectData.id) {
					// this.getChatByPageList()
					// return
					if (this.isChangeBottom) {
						this.chatList = []
						this.chatImgs = []
						this.pageNum = 1
						this.pageSize = 20
						this.getChatList(1)
						this.msgReag(this.msgObjectData)
						//获取最后一条
						var lastMsg = this.chatList[this.chatList.length - 1]
						if (lastMsg.sendId == this.userId) {
							this.gotoScrollBottom(30)
						} else {
							this.gotoScrollBottom(30, false)
							//this.$refs.myChatRef.showNewTips()
						}
				
					} else {
						this.chatList = []
						this.chatImgs = []
						//当前查询条数
						var pageAllSize = this.pageSize * this.pageNum
						this.pageNum = 1
						this.pageSize = pageAllSize + 1
						this.getChatList(1)
						this.msgReag(this.msgObjectData)
						//获取最后一条
						var lastMsg = this.chatList[this.chatList.length - 1]
				
						// if (lastMsg.msgType == 21) {
						// 	return
						// }
				
						if (lastMsg.sendId == this.userId) {
							this.gotoScrollBottom(30)
						} else {
							this.gotoScrollBottom(30, false)
							//this.$refs.myChatRef.showNewTips()
						}
					}
				
				}
			},
			notTopMsgData() {
				/* var newMsg = this.notTopMsgData[0]
				if (newMsg.type == 2 && newMsg.id == this.msgObjectData.id) {
					this.chatList = []
					this.chatImgs = []
					var pageAllSize = this.pageSize * this.pageNum
					this.pageNum = 1
					this.pageSize = pageAllSize + 1
					this.getChatList(1)
					this.msgReag(this.msgObjectData)
					//获取最后一条
					var lastMsg = this.chatList[this.chatList.length - 1]

					if (lastMsg.sendId == this.userId) {
						this.gotoScrollBottom(50)
					} else {
						//this.isShowGoto = true
						this.gotoScrollBottom(50, false)
					}
				} */

				var newMsg = this.notTopMsgData[0]
				if (newMsg.type == 2 && newMsg.id == this.msgObjectData.id) {
					// this.getChatByPageList()
					// return
					if (this.isChangeBottom) {
						this.chatList = []
						this.chatImgs = []
						this.pageNum = 1
						this.pageSize = 20
						this.getChatList(1)
						this.msgReag(this.msgObjectData)
						//获取最后一条
						var lastMsg = this.chatList[this.chatList.length - 1]
						if (lastMsg.sendId == this.userId) {
							this.gotoScrollBottom(30)
						} else {
							this.gotoScrollBottom(30, false)
							//this.$refs.myChatRef.showNewTips()
						}

					} else {
						this.chatList = []
						this.chatImgs = []
						//当前查询条数
						var pageAllSize = this.pageSize * this.pageNum
						this.pageNum = 1
						this.pageSize = pageAllSize + 1
						this.getChatList(1)
						this.msgReag(this.msgObjectData)
						//获取最后一条
						var lastMsg = this.chatList[this.chatList.length - 1]

						// if (lastMsg.msgType == 21) {
						// 	return
						// }

						if (lastMsg.sendId == this.userId) {
							this.gotoScrollBottom(30)
						} else {
							this.gotoScrollBottom(30, false)
							//this.$refs.myChatRef.showNewTips()
						}
					}


				}
				//this.pageSize = 20
			}
		},
		methods: {
			...mapActions('m_chat', ['setMsgList', 'msgReag', 'msgGoTop', 'clearMsgByList', 'addChatData',
				'readRedPkgStore', 'removeMsvById'
			]),

			//1，查询指定页面数据
			getChatList(page, isgotoBottom = false) {
				for (var i = 0; i < this.chatData.length; i++) {
					if (this.chatData[i].id == this.msgObjectData.id && this.chatData[i].type == this.msgObjectData.type) {
						//1，计算出 总共能分成多少页
						var msgListLength = Math.ceil(this.chatData[i].list.length / this.pageSize)

						//2，如果要查看的页数大于总共分成的页数 或者 和该对象历史聊天数为0，返回没有更多数据可查
						if (page > msgListLength || this.chatData[i].list.length == 0) {
							console.log('没有消息')
							continue;
						}

						//3，获取 指定页数开始查询的list下标（如需要查询第2页 则从下标为10的数据开始往后查10个数据）
						var forPage = (page - 1) * this.pageSize
						for (forPage; forPage < (this.pageSize * page); forPage++) {
							//4，如果 总长度，大于 递增下标，则可以添加数据进行展示（如果小于或等于，代表没有更多顺序，直接返回就可以了）
							if (this.chatData[i].list.length > forPage) {

								//将消息组装
								this.chatList.unshift(this.chatData[i].list[forPage])

								//判断消息类型是否为图片
								if (this.chatData[i].list[forPage].msgType == 2) {
									this.chatImgs.unshift(this.chatData[i].list[forPage].news)
								}
							} else {
								continue;

								/* if (isgotoBottom) {
									this.gotoScrollBottom(130)
								} */
							}
						}

						/* if (isgotoBottom) {
							this.gotoScrollBottom(100)
						} */
					}
				}

			},
			//1.2，加载更多信息
			getChatListByPage() {
				this.pageNum++
				this.getChatList(this.pageNum)

				setTimeout(() => {
					// uni.stopPullDownRefresh()
					this.$refs.myChatRef.closeRefreshScroll()
				}, 500)
			},

			//2，查询聊天对象信息
			getUserInfo(fid) {
				if (fid == this.userId) {
					this.isMe = true
					return
				}
				var that = this
				queryFriendRemarks(parseInt(fid), 2).then(res => {
					if (res.data.pubInfo.code !== 0) {
						//uni.$showMsg(res.data.pubInfo.message);
						if (res.data.pubInfo.message == '未建立关系') {
							that.isGx = false
							that.isShowSend = true
						}
						return
					}
					//2.3，参数保存
					var busInfo = res.data.busInfo
					that.friendName = busInfo

					wx.setNavigationBarTitle({
						title: busInfo
					})

					queryIsBlack(that.userId, fid).then(res => {
						if (res.data.pubInfo.code !== 0) {
							return uni.$showMsg(res.data.pubInfo.message)
						}
						//console.log(res.data.busInfo)
						if (res.data.busInfo == '2') {
							that.isBlackUser = true
						}

						//消息置顶
						that.$refs.myChatRef.closeRefreshScroll()
					})
				})
			},

			//3，发送文本消息消息
			sendMsg(data) {
				//console.log(data)
				this.socketSendMsg(data, 0)
			},
			//4，消息滚动到底部
			gotoScrollBottom(time = 50, isSendMsg = true) {
				//console.log(123)
				this.$refs.myChatRef.initScrollBar(time, isSendMsg)
			},

			//5，跳转好友设置页面
			gotoUserSet(item) {
				if (item.sendId == this.userId) {
					//用户点击自己的头像
					return
				}
				var req = {
					id: item.sendId,
					nickname: item.sendNickname,
					head: item.sendHead,
					type: 2, //用户单聊类型
				}
				uni.navigateTo({
					url: '/subpkg/msg/user/user-describe/user-describe?msgObject=' + JSON.stringify(req),
				})
			},

			//6，红包相关
			//6.1，点击红包消息
			showRedPkg(item) {
				//判断是否实名认证 如果没有实名认证无法下单
				if (!uni.getStorageSync('identifyCheck')) {
					return uni.$showMsg('请先进行实名认证！')
				}
				//console.log(item)
				//this.isShowHb = true
				this.showHbMsg = item
				if (!item.isRedRead) {
					var req = item
					req.type = 2
					req.id = this.msgObjectData.id
					//红包已读
					this.readRedPkgStore(req)
				}

				if (this.userId != item.sendId) {
					queryRedPkgById(item.redPkgId).then(res => {
						if (res.data.pubInfo.code !== 0) {
							return uni.$showMsg(res.data.pubInfo.message);
						}
						//2.3，参数保存
						var busInfo = res.data.busInfo
						if (busInfo.surplusAmount > 0 && busInfo.surplusNum > 0) {
							//如果不是自己发送的红包（展示抢红包特效）
							this.isShowHb = true
						} else {
							//没有剩余红包，直接跳转红包详情页
							return uni.navigateTo({
								url: '/subpkg/msg/red-pkg/red-pkg-detail/red-pkg-detail?hbId=' + item
									.redPkgId
							})
						}
						//console.log(busInfo)
					})

				} else {
					//如果是自己发的红包直接跳转红包详情页面
					uni.navigateTo({
						url: '/subpkg/msg/red-pkg/red-pkg-detail/red-pkg-detail?hbId=' + item.redPkgId +
							'&nickname=' + this.friendName
					})

				}
			},
			//6.2，关闭红包
			closeHbFun() {
				this.isShowHb = false
			},
			//6.3，开始抢红包
			openHbFun(item) {
				var that = this;
				var animation = uni.createAnimation({
					duration: 1000,
					timingFunction: 'ease',
				})
				that.openbrnanimation = animation;
				// animation.rotate3d(0,1,0,360).step();
				animation.rotateY(360).step();
				that.openbrnanimation = animation.export();
				robByUser(item.redPkgId).then(res => {
					if (res.data.pubInfo.code !== 0) {
						return uni.$showMsg(res.data.pubInfo.message);
					}
					that.isShowHb = false
					//that.rbagmodelshow = false;
					that.openrbagmodelshow = true;
					that.openbrnanimation = {};

					//跳转到详情页面
					setTimeout(() => {
						return uni.navigateTo({
							url: '/subpkg/msg/red-pkg/red-pkg-detail/red-pkg-detail?hbId=' + item
								.redPkgId + '&nickname=' + this.friendName
						})
					}, 500)

				})
			},

			//7，删除消息
			closeUserMsg(showPopChatItem) {
				//删除消息
				for (var i = 0; i < this.chatList.length; i++) {
					if (this.chatList[i].msgId == showPopChatItem.msgId) {
						this.chatList.splice(i, 1)
						continue;
					}
				}
				this.removeMsvById(showPopChatItem)
				return
			},

			//8，撤回消息
			withdrawUserMsg(showPopChatItem) {
				let data = {
					msg: '撤回一条消息',
					types: 11
				}
				this.socketSendMsg(data, showPopChatItem.msgId)
			},

			//9，发起添加好友请求
			sendAddUser() {
				var reqData = {
					type: this.$chatType.ADD_FRIEND,
					msg: {
						senderId: this.userId,
						senderName: this.nickname,
						senderHead: this.head,
						receiverId: this.msgObjectData.id,
						message: '添加好友',
						sysType: 2,
					}
				}

				uni.myWebsocket.socketTask.send({
					data: JSON.stringify(reqData),
					async success() {
						return uni.$showMsg('发送成功');
					},
					fail(e) {
						uni.$showMsg('发送失败！');
					}
				});
			},

			//10，语音播放
			handleAudio(item) {
				this.innerAudioContent.paused ? this.playAudio(item) : this.stopAudio(item);

				this.innerAudioContent.onPlay(() => {
					//console.log('播放')
					//this.innerAudioContent.paused = false
				})

				this.innerAudioContent.onEnded(() => {
					//console.log('暂停播放')
					//this.innerAudioContent.paused = true
					this.stopAudio(item)
				})
			},
			//10.1，播放音频
			playAudio(item) {
				//console.log(item)
				var voice = JSON.parse(item.news)
				var voiceUrl = voice.voice
				this.innerAudioContent.src = voiceUrl
				this.innerAudioContent.play()

				for (var i = 0; i < this.chatList.length; i++) {
					if (this.chatList[i].msgId == item.msgId && this.chatList[i].time == item.time) {
						var oldVoice = JSON.parse(this.chatList[i].news)
						oldVoice.anmitionPlay = true
						this.chatList[i].news = JSON.stringify(oldVoice)
					}
				}

			},
			//10.2，停止音频
			stopAudio(item) {
				var voice = JSON.parse(item.news)
				this.innerAudioContent.src = ''
				this.innerAudioContent.stop()
				for (var i = 0; i < this.chatList.length; i++) {
					if (this.chatList[i].msgId == item.msgId && this.chatList[i].time == item.time) {
						var oldVoice = JSON.parse(this.chatList[i].news)
						oldVoice.anmitionPlay = false
						this.chatList[i].news = JSON.stringify(oldVoice)
					}
				}
			},

			//websocket
			//1，socket发送消息
			socketSendMsg(e, msgId) {
				if (!this.isGx) {
					return uni.$showMsg('对方不是你的好友！');
				}
				if (this.isBlackUser) {
					return uni.$showMsg('对方已将您加入黑名单！');
				}

				var that = this
				var nowTime = getNowTime() + ''

				//消息组装
				let msgData = {
					type: this.$chatType.CHAT_FRIEND,
					msg: {
						id: msgId || 0,
						senderId: this.userId,
						senderHead: this.head, //头像
						senderName: this.nickname,
						types: e.types, //消息类型 （1文本，2图片连接，3音频，4红包）
						message: e.msg, //消息 
						time: nowTime,
						receiverId: this.msgObjectData.id,
						receiverHead: this.msgObjectData.head,
						receiverName: this.msgObjectData.nickname
					}
				}
				//console.log(msgData)
				uni.myWebsocket.socketTask.send({
					data: JSON.stringify(msgData),
					async success() {
						console.log('发送成功')
					},
					fail(e) {
						uni.$showMsg('发送失败！');
						console.log(e)
					}
				});
			},
			//2，消息监听
			listenSocketMsg() {
				if (uni.myWebsocket == undefined || uni.myWebsocket == '' || uni.myWebsocket == null) {
					//连接上websocket
					uni.$connectSocketInit.connectSocket(uni.$nettyPort)
				}
			}

		},
		onLoad(e) {
			var msgObject = JSON.parse(e.msgObject)
			this.msgObjectData = msgObject

			//消息已读
			this.msgReag(msgObject)

			//获取聊天对象信息
			this.getUserInfo(msgObject.id)

			wx.setNavigationBarTitle({
				title: msgObject.nickname
			})

			//消息监听
			this.listenSocketMsg()
		},
		mounted() {
			//获取第一页聊天信息
			this.getChatList(1, true)

			this.gotoScrollBottom(30)
		},
		activated() {
			//this.gotoScrollBottom(50)
		},
		onShow() {
			//消息已读
			this.msgReag(this.msgObjectData)
			//this.gotoScrollBottom()
			//this.getUserInfo(this.msgObjectData.id)
			this.listenSocketMsg()


		},
		onNavigationBarButtonTap(e) {
			//console.log(e)
			return uni.navigateTo({
				url: '/subpkg/msg/set/set-user/set-user?msgObject=' + JSON.stringify(this.msgObjectData)
			})
		},
		onHide() {
			console.log('隐藏')
			this.innerAudioContent.stop()
		},
		onBackPress() {
			console.log('隐藏2')
			this.innerAudioContent.stop()
		},
		onUnload() {
			console.log('隐藏3')
			this.innerAudioContent.stop()
		}
	}
</script>

<style>

</style>